﻿using RpcCacheClient.Helper;
using RpcClient.Interface;
using RpcHelper;
using RpcSync.Collect;
using RpcSync.Model;
using RpcSync.Service.Interface;

namespace RpcSync.Service.Tran
{
    [RpcClient.Attr.ClassLifetimeAttr(RpcClient.Attr.ClassLifetimeType.单例)]
    internal class RollbackTranService : IRollbackTranService
    {
        private readonly IDataQueueHelper<Guid> _Queue = null;
        private ISingleTranService _SingleTran;
        private IUnityCollect _Unity;
        public RollbackTranService(IUnityCollect unity, ISingleTranService singleTran)
        {
            this._Unity = unity;
            this._SingleTran = singleTran;
            string name = string.Concat("TranRollBack_", RpcClient.RpcClient.CurrentSource.RegionId);
            _Queue = new RedisDataQueue<Guid>(name, _Rollback);
        }

        private void _Rollback(Guid tranId)
        {
            ITransactionCollect tranCollect = _Unity.Resolve<ITransactionCollect>();
            RegTranState tran = tranCollect.GetTranState(tranId);
            if (tran.TranStatus != RpcModel.TransactionStatus.待回滚)
            {
                return;
            }
            Guid[] ids = tranCollect.TranRollbackLock(tranId);
            if (!ids.IsNull())
            {
                this._SingleTran.AddQueue(ids);
            }
        }

        public void AddQueue(Guid tranId)
        {
            _Queue.AddQueue(tranId);
        }
    }
}
